<template>
  <div>
    <script :id="editorId" name="content" type="text/plain"></script>
  </div>
</template>
<script>
  import '@static/ueditor/ueditor.config'
  import '@static/ueditor/ueditor.all'
  import '@static/ueditor/lang/zh-cn/zh-cn'
  import {mapActions} from 'vuex'
  export default {
    data () {
      return {
        editorId: 'editorContainer'
      }
    },
    mounted () {
      window.ue && window.ue.destroy()
      this.initEditor()
    },
    props: ['content'],
    watch: {
      'content': function (now) {
        this.setContent(now)
      }
    },
    computed: {},
    methods: {
      ...mapActions(['setShortLink']),
      // 初始化编辑器
      initEditor () {
        window.ue = this.ue = UE.getEditor(this.editorId, {
          toolbars: [
              ['undo', 'redo', '|', 'fontsize', '|', 'blockquote', 'horizontal', '|', 'removeformat', 'formatmatch', 'link', 'unlink'],
              ['bold', 'italic', 'underline', 'forecolor', 'backcolor', '|', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'insertorderedlist', 'insertunorderedlist', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter']
          ],
          initialFrameWidth: 'auto',
          initialFrameHeight: 182,
          minFrameWidth: 770,
          minFrameHeight: 300,
          allHtmlEnabled: true,
          scaleEnabled: false,
          wordCount: false,
          elementPathEnabled: false,
          autoFloatEnabled: false
        })
        this.ue.addInputRule(function (root) {
          root.getNodesByTagName('img').forEach(node => {
            const src = node.getAttr('data-src') || node.getAttr('_src')
            node.setAttr('src', src)
          })
        })
        this.ue.addListener('contentChange', () => {
          this.$emit('contentChange', this.ue.getContent())
        })
      },
      execCommand (command, str) {
        this.ue.execCommand(command, str)
      },
      setContent (cont) {
        if (!this.ue.isReady) {
          this.ue.addListener('ready', () => {
            this.ue.setContent(cont)
          })
        } else {
          this.ue.setContent(cont)
        }
      },
      getEditorCont () {
        return this.ue.getContent()
      }
    }
  }
</script>
<style lang="scss">
  #editorContainer .edui-default .edui-toolbar{
    line-height: 18px;
    padding: 5px 10px 0;
  }
</style>
